package com.eminem.filter;

import com.eminem.service.UserService;
import com.eminem.service.impl.UserServletimpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

@WebFilter("/index.jsp")
public class SingFilter implements Filter {

    private UserService userService = new UserServletimpl();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            if ("username".equals(cookie.getName())){
                HttpSession session = req.getSession();
                String sid = session.getId();
                Map<String, Object> map = userService.findUserInfo(cookie.getValue());
                session.setAttribute("UserInfo",map);
                session.setAttribute(sid,map.get("userId").toString());
                resp.sendRedirect(req.getContextPath()+"/html/home.jsp");
                return;
            }
        }
        filterChain.doFilter(req,resp);
    }

    @Override
    public void destroy() {

    }
}
